"""
音乐播放器功能函数
为LLM提供音乐播放的Function Calling接口
"""

import logging
from typing import Dict, Any
from ..music_player import get_music_player
from .function_registry import FunctionRegistry

logger = logging.getLogger(__name__)


@FunctionRegistry.register_function('music_list', '获取可播放的音乐列表')
def music_list_func() -> str:
    """获取音乐列表"""
    try:
        player = get_music_player()
        music_list = player.list_music()
        
        if not music_list:
            return "很抱歉，当前没有可播放的音乐。请将音乐文件放入music目录中，并确保已安装pygame库：pip install pygame==2.5.2"
        
        # 生成友好的回复
        music_names = []
        for music_file in music_list:
            # 去掉文件扩展名
            name = music_file.rsplit('.', 1)[0]
            music_names.append(name)
        
        return f"当前可播放的音乐有：{', '.join(music_names)}，共{len(music_names)}首歌曲。"
        
    except Exception as e:
        if "pygame库未安装" in str(e):
            return "音乐播放器需要pygame库支持。请先安装：pip install pygame==2.5.2"
        logger.error(f"获取音乐列表失败: {e}")
        return "获取音乐列表时出现了问题，请稍后重试。"


@FunctionRegistry.register_function('music_play', '播放指定的歌曲')
def music_play_func(music_name: str) -> str:
    """播放指定歌曲"""
    try:
        player = get_music_player()
        result = player.play_music(music_name)
        return result
        
    except Exception as e:
        logger.error(f"播放音乐失败: {e}")
        return f"播放音乐时出现了问题：{str(e)}"


@FunctionRegistry.register_function('music_play_random', '随机播放一首歌曲')
def music_play_random_func() -> str:
    """随机播放歌曲"""
    try:
        player = get_music_player()
        result = player.play_random_music()
        return result
        
    except Exception as e:
        if "pygame库未安装" in str(e):
            return "音乐播放器需要pygame库支持。请先安装：pip install pygame==2.5.2"
        logger.error(f"随机播放失败: {e}")
        return f"随机播放时出现了问题：{str(e)}"


@FunctionRegistry.register_function('music_stop', '停止当前播放的音乐')
def music_stop_func() -> str:
    """停止播放音乐"""
    try:
        player = get_music_player()
        result = player.stop_music()
        return result
        
    except Exception as e:
        logger.error(f"停止音乐失败: {e}")
        return f"停止音乐时出现了问题：{str(e)}"


@FunctionRegistry.register_function('music_volume_set', '设置音乐播放音量')
def music_volume_set_func(volume: float) -> str:
    """设置音量"""
    try:
        # 验证音量参数
        if not isinstance(volume, (int, float)):
            return "音量参数必须是数字"
        
        if volume < 0 or volume > 1:
            return "音量范围应在0.0到1.0之间"
        
        player = get_music_player()
        result = player.set_volume(volume)
        return result
        
    except Exception as e:
        if "pygame库未安装" in str(e):
            return "音乐播放器需要pygame库支持。请先安装：pip install pygame==2.5.2"
        logger.error(f"设置音量失败: {e}")
        return f"设置音量时出现了问题：{str(e)}"


@FunctionRegistry.register_function('music_volume_up', '增加音乐播放音量')
def music_volume_up_func(step: float = 0.1) -> str:
    """增加音量"""
    try:
        # 验证步长参数
        if not isinstance(step, (int, float)):
            return "音量步长必须是数字"
        
        if step <= 0 or step > 1:
            return "音量步长应在0到1之间"
        
        player = get_music_player()
        result = player.increase_volume(step)
        return result
        
    except Exception as e:
        if "pygame库未安装" in str(e):
            return "音乐播放器需要pygame库支持。请先安装：pip install pygame==2.5.2"
        logger.error(f"增加音量失败: {e}")
        return f"增加音量时出现了问题：{str(e)}"


@FunctionRegistry.register_function('music_volume_down', '减少音乐播放音量')
def music_volume_down_func(step: float = 0.1) -> str:
    """减少音量"""
    try:
        # 验证步长参数
        if not isinstance(step, (int, float)):
            return "音量步长必须是数字"
        
        if step <= 0 or step > 1:
            return "音量步长应在0到1之间"
        
        player = get_music_player()
        result = player.decrease_volume(step)
        return result
        
    except Exception as e:
        if "pygame库未安装" in str(e):
            return "音乐播放器需要pygame库支持。请先安装：pip install pygame==2.5.2"
        logger.error(f"减少音量失败: {e}")
        return f"减少音量时出现了问题：{str(e)}"


@FunctionRegistry.register_function('music_status', '获取当前音乐播放状态')
def music_status_func() -> str:
    """获取播放状态"""
    try:
        player = get_music_player()
        status = player.get_current_status()
        
        if status["is_playing"] and status["current_music"]:
            music_name = status["current_music"].rsplit('.', 1)[0]
            volume_percent = int(status["volume"] * 100)
            return f"🎵 正在播放《{music_name}》，音量：{volume_percent}%"
        else:
            volume_percent = int(status["volume"] * 100)
            return f"⏸ 当前没有播放音乐，音量设置为{volume_percent}%，共有{status['music_count']}首歌曲可供播放。"
        
    except Exception as e:
        if "pygame库未安装" in str(e):
            return "音乐播放器需要pygame库支持。请先安装：pip install pygame==2.5.2"
        logger.error(f"获取播放状态失败: {e}")
        return "获取播放状态时出现了问题。"


def parse_volume_value(value) -> tuple:
    """解析音量值，支持多种格式"""
    if isinstance(value, (int, float)):
        v = float(value)
        if v < 0:
            return 0.0, 'mute'
        elif v > 1:
            return 1.0, 'max'
        else:
            return v, 'normal'
    
    if isinstance(value, str):
        v = value.strip().lower()
        
        # 支持中文描述
        if v in ['静音', 'mute']:
            return 0.0, 'mute'
        elif v in ['最大', '最大音量', '全开']:
            return 1.0, 'max'
        elif v in ['最小', '最小音量']:
            return 0.0, 'mute'
        elif v in ['一半', '中等', '50%']:
            return 0.5, 'normal'
        
        # 支持百分比
        if v.endswith('%'):
            try:
                percent = float(v[:-1])
                if percent <= 0:
                    return 0.0, 'mute'
                elif percent >= 100:
                    return 1.0, 'max'
                else:
                    return percent / 100.0, 'normal'
            except ValueError:
                pass
        
        # 尝试直接转换为数字
        try:
            f = float(v)
            if f < 0:
                return 0.0, 'mute'
            elif f > 1:
                return 1.0, 'max'
            else:
                return f, 'normal'
        except ValueError:
            pass
    
    # 默认值
    return 0.5, 'normal'


@FunctionRegistry.register_function('music_volume_set_smart', '智能设置音乐音量（支持数字、百分比、中文描述）')
def music_volume_set_smart_func(value) -> str:
    """智能设置音量，支持多种输入格式"""
    try:
        volume, vtype = parse_volume_value(value)
        player = get_music_player()
        result = player.set_volume(volume)
        
        # 根据输入类型优化回复
        if vtype == 'mute':
            return "音乐已为您静音。"
        elif vtype == 'max':
            return "音乐音量已调到最大。"
        else:
            volume_percent = int(volume * 100)
            return f"音乐音量已设置为{volume_percent}%。"
        
    except Exception as e:
        logger.error(f"智能设置音量失败: {e}")
        return f"设置音量时出现了问题：{str(e)}"